package com.elitetyc.customview.digitclock;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.widget.RemoteViews;

import com.elitetyc.customview.R;
import com.elitetyc.customview.activity.LdsViewActivity;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.LogRecord;

/**
 * Created by elitetyc on 2019/6/11.
 * Describe:
 */
public class DigitClock extends AppWidgetProvider {

    private Timer timer = new Timer();
    private int[] appWidgetIds;
    private AppWidgetManager appWidgetManager;
    private Context context;
    private TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            handler.sendEmptyMessage(1);
        }
    };

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    int n = appWidgetIds.length;
                    for (int i = 0; i < n; i++) {
                        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.view_digitclock);
                        DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
                        views.setTextViewText(R.id.tv_time,dateFormat.format(new Date()));
                        views.setOnClickPendingIntent(R.id.widget_main,getPendingIntent());
                        appWidgetManager.updateAppWidget(appWidgetIds[i],views);
                    }
                    break;
            }
        }
    };

    private PendingIntent getPendingIntent() {
        Intent intent = new Intent(context, LdsViewActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context,0,intent,0);
        return pendingIntent;
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
//        super.onUpdate(context, appWidgetManager, appWidgetIds);
        this.appWidgetIds = appWidgetIds;
        this.appWidgetManager = appWidgetManager;
        this.context = context;
        timer = new Timer();
        timer.schedule(timerTask,0,1000);
    }
}
